package cc.opcol.iot.server.repo;

import cc.opcol.iot.server.domain.JsEventHandle;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class MongoEventHandleRepository  {

    @Autowired
    MongoTemplate mongoTemplate;

    public static final String NAMESPACE="jsp_handle";

    Gson gson=new Gson();

    public List<JsEventHandle> queryAllByIdDesc() {
        List<JsEventHandle> list=new ArrayList<>();
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"_id"));
        list= mongoTemplate.find(query,JsEventHandle.class,NAMESPACE);
        return list;
    }

    public JsEventHandle getOne(Long id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Map map=mongoTemplate.findOne(query,Map.class,NAMESPACE);
        if(map!=null){
            return gson.fromJson((String)map.get("json"),JsEventHandle.class);
        }
        return null;
    }

}
